<?php
/**
 * NOTICE OF LICENSE
 *
 * THIS SOURCE FILE IS PART OF EVEBIT'S PRIVATE PROJECT.
 * 
 * DO NOT USE THIS FILE IN OTHER PLACE.
 *
 * @category  EveBit_Library_Translate
 * @package   Adapter
 * @author    Zhang MingYue <zhang.mingyue@evebit.com>
 * @version   $$Id: DbTranslate.php 291 2011-04-11 02:52:19Z chang.zhenhua $$
 * @copyright Copyright (c) 2008 Evebit Inc. China (http://www.evebit.com)
 */

/**
 * @see Zend_Translate_Adapter
 */
/** Zend_Locale */
require_once 'Zend/Locale.php';

/** Zend_Translate_Adapter */
require_once 'Zend/Translate/Adapter.php';

/**
 *   @docinfo
 * Customer Adapter extend Zend_Translate_Adapter Abstract Class
 * @category   EveBit_Library_Translate
 * @package    Adapter
 * @copyright Copyright (c) 2008 Evebit Inc. China (http://www.evebit.com)
 */
class Evebit_Translate_Adapter_DbTranslate extends Zend_Translate_Adapter {
    private $_data        = array();
	private $_adpteroptions =array();
	private $_automatic = false;
	/**
     * Internal cache for all adapters
     * @var Zend_Cache_Core
     */
    protected static $_cache     = null;

    /**
     * Internal value to remember if cache supports tags
     *
     * @var boolean
     */
    private static $_cacheTags = false;
   
	/**
	  * Init translation data in evebit function use application to init the base params
     *  
     *  include db info 
     * @param  mixed              $data
     * @param  string|Zend_Locale $locale
     * @param  array              $options (optional)
     * @return array
	 * @see Zend_Translate_Adapter::_loadTranslationData()
	 */
    protected function _loadTranslationData($data, $locale, array $options = array())
    {
    	require_once 'Zend/Cache.php';
    	
        $this->_data = array();
    	if (!Zend_Registry::isRegistered('Zend_Cache')) {
			
	        if(isset($options['cachetime']))
	        {
				$frontendOptions = array(
				   'lifeTime' => $options['cachetime'],                  // cache lifetime of 30 seconds
				   'automatic_serialization' => true  // this is the default anyway s
				);
	        }
			else 
			{
				$frontendOptions = array(
				   'lifeTime' => 300,                  // cache lifetime of 30 seconds
				   'automatic_serialization' => true  // this is the default anyway s
				);
			}
			if(isset($options['cachepath']))
			{
				$backendOptions = array('cache_dir' => $options['cachepath']);
			}
			else 
			{
				$backendOptions = array('cache_dir' => RP.'/var/cache/');
			}		
			$cache = Zend_Cache::factory('Core',
	                             'File',
	                             $frontendOptions,
	                             $backendOptions);
    		Zend_Registry::set('Zend_Cache', $cache);
		}
		else 
			$cache = Zend_Registry::get('Zend_Cache');
       
		if(!$result = $cache->load($options['cachename'])) {
            if(isset($options['db'])&&isset($options['db']['adapter'])&&isset($options['db']['params']))
			{
				$db = Zend_Db::factory($options['db']['adapter'], $options['db']['params']);
	    		$sql = $db->quoteInto(
			    	'SELECT * FROM '.trim($data),'',''
				);
				$result = $db->query($sql);
				$rows = $result->fetchAll();
	    		$sql = $db->quoteInto(
			    	'SELECT * FROM locale_language','',''
				);
				$result = $db->query($sql);
				$type = $result->fetchAll();
				$temp_languages=array();
				$outdata=array();
				if(!empty($type))
				{
					for($i=0;$i<count($type);$i++)
					{
						$trandata=array();
						$temp_languages[$type[$i]['name']]=$type[$i]['code'];
						for($j=0;$j<count($rows);$j++)
						{
							if($rows[$j]['locale']==$type[$i]['code'])
							{
								if($rows[$j]['state']!=3&&$type[$i]['state']==0)
								{
									$trandata[$rows[$j]['source_language']]=$rows[$j]['target'];
								}
								else 
								{
									$trandata[$rows[$j]['source_language']]=$rows[$j]['source_language'];
								}
							}
						}
						$outdata[$type[$i]['code']]=$trandata;
				        $this->_data[$type[$i]['code']] = $trandata;
					}
				}
			Evebit_Application::getSession()->languages=$temp_languages;
			$cache->save($outdata, ''.$options['cachename']);
			$cache->save($temp_languages, ''.$options['cachelanguage']);
			}
			else 
				throw new Zend_Translate_Exception('Error Connect DB');
		} 
		else {
		    foreach ($result as $key => $value)
		    {
		    	$this->_data[$key]=$value;
		    }
		   	if(empty(Evebit_Application::getSession()->languages))
		   	{
		    	if(!$temp=$cache->load($options['cachelanguage']))
		    	{
		    		if(isset($options['db'])&&isset($options['db']['adapter'])&&isset($options['db']['params']))
					{
						$db = Zend_Db::factory($options['db']['adapter'], $options['db']['params']);
			    		$sql = $db->quoteInto(
					    	'SELECT * FROM locale_language','',''
						);
						$result = $db->query($sql);
						$type = $result->fetchAll();
						$temp_languages=array();
						if(!empty($type))
						{
							for($i=0;$i<count($type);$i++)
							{
								$temp_languages[$type[$i]['name']]=$type[$i]['code'];
							}
						}
						Evebit_Application::getSession()->languages=$temp_languages;
				   		$cache->save($temp_languages, ''.$options['cachelanguage']);
					}
					else 
						throw new Zend_Translate_Exception('Error Connect DB');
		    	}
		    	else
		    	{
		    		Evebit_Application::getSession()->languages=$temp;
		    	}
		   	}
		}
        return $this->_data;
    }

    /**
	  * AutoInsert Translate Resource to Db
     *  
     *  
     * @param  string              $arg_msg
     * @param  Evebit_Translate_Adapter_DbTranslate  $arg_translate
     * @param  Zend_Locale             $arg_locale
	 */
	public function insertTranslaterData($arg_msg,$arg_translate,$arg_locale)
	{
		if($arg_msg&&$arg_translate&&$arg_locale)
		{
			$data=$arg_translate->getMessageId($arg_msg,$arg_locale);
			if($data===false)
			{
				$option=$arg_translate->getAdapter()->getOptions();
				$db = Zend_Db::factory($option['db']['adapter'], $option['db']['params']);
	    		$sql = $db->quoteInto(
			    	'SELECT * FROM '.$option['content'].' where source_language = '.$db->quote($arg_msg).' and locale= '.'"'.$option['locale'].'"','',''
				);
				$result = $db->query($sql);
				$rows = $result->fetchAll();
				
				if(empty($rows))
				{
					$sql = $db->quoteInto(
				    	'SELECT * FROM locale_language where code = ?',''.$option['locale']
					);
					$result = $db->query($sql);
					$rows = $result->fetchAll();
					$name=$rows[0]['name'];
					$row = array (
					    'locale'    => $arg_locale,
					    'source_language' => $arg_msg,
						'target' => $arg_msg,
		    			'locale_name' => $name,
						'state'=>2,
					);
					$table = $option['content'];
					
					$rows_affected = $db->insert($table, $row);
					$last_insert_id = $db->lastInsertId();
					
					if ( ! $last_insert_id ) {
						echo "<script> alert('" . $db->getErrorMsg() . "'); window.history.go(-1); </script>\n";
						exit();
					}
				}
			}
		}
	}
	
	public function setLocale($locale){
		try {
            $locale = Zend_Locale::findLocale($locale);
        } catch (Zend_Locale_Exception $e) {
            require_once 'Zend/Translate/Exception.php';
            throw new Zend_Translate_Exception("The given Language ({$locale}) does not exist", 0, $e);
        }
        if (!isset($this->_translate[$locale])) {
            $temp = explode('_', $locale);
            if (!isset($this->_translate[$temp[0]]) and !isset($this->_translate[$locale])) {
                if (!$this->_options['disableNotices']) {
                    if ($this->_options['log']) {
                       // $this->_options['log']->log("The language '{$locale}' has to be added before it can be used.", $this->_options['logPriority']);
                    } else {
                       //trigger_error("The language '{$locale}' has to be added before it can be used.", E_USER_NOTICE);
                    }
                }
            }

            $locale = $temp[0];
        }
        
        if ($this->_options['locale'] != $locale) {
            $this->_options['locale'] = $locale;

            if (isset(self::$_cache)) {
                $id = 'Zend_Translate_' . $this->toString() . '_Options';
                if (self::$_cacheTags) {
                    self::$_cache->save($this->_options, $id, array($this->_options['tag']));
                } else {
                    self::$_cache->save($this->_options, $id);
                }
            }
        }

        return $this;
    }
    /**
     * Returns the adapter name
     *
     * @return string
     */
    public function toString()
    {
        return "DbTranslate";
    }
}